#pragma once
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string>
#include <sys/time.h>
#include <sys/resource.h>

#include "../comm/log.hpp"
#include "../comm/util.hpp"

namespace ns_runner
{
    using namespace ns_log;

    class Runner
    {
    public:
        Runner(){}
        ~Runner(){}

    public:
        // 传入可执行文件名，运行可执行文件
        static int Run(const std::string &file_name, const int cpu_limit, const int mem_limit)
        {
            // 打开三个文件：输入、输出、错误
            umask(0);
            int in_id = open(ns_util::PathUtil::RunIn(file_name).c_str(), O_CREAT | O_RDONLY, 0644);
            int out_id = open(ns_util::PathUtil::RunOut(file_name).c_str(), O_CREAT | O_WRONLY, 0644);
            int err_id = open(ns_util::PathUtil::RunErr(file_name).c_str(), O_CREAT | O_WRONLY, 0644);

            if(in_id < 0 || out_id < 0 || err_id < 0)
            {
                LOG(ERROR) << " -> 运行时文件打开失败！" << "\n";
                return -1;
            }

            pid_t pid = fork(); // 创建子进程

            if(pid < 0)
            {
                close(in_id);
                close(out_id);
                close(err_id);

                LOG(ERROR) << " -> 子进程创建失败！" << "\n";
                return -2;
            }
            else if(pid == 0)
            {
                // 子进程
                // 重定向
                dup2(in_id, 0);
                dup2(out_id, 1);
                dup2(err_id, 2);

                // 资源限制
                SetLimit(cpu_limit, mem_limit);

                // 进程替换
                execl(ns_util::PathUtil::Exe(file_name).c_str(), ns_util::PathUtil::Exe(file_name).c_str(), nullptr);

                LOG(ERROR) << " -> 进程替换失败！" << "\n";
                exit(1);
            }
            else
            {
                // 父进程
                close(in_id);
                close(out_id);
                close(err_id);

                int stat = 0;
                waitpid(pid, &stat, 0);
                LOG(INFO) << " -> " << ns_util::PathUtil::Exe(file_name) << " 运行成功！" << "\n";

                return stat & 0x7f;
            }
        }

        // 资源限制 执行时间(s) 执行内存(KB)
        static void SetLimit(const int cpu_limit, const int mem_limit)
        {
            struct rlimit r_cpu;
            struct rlimit r_mem;
            r_cpu.rlim_cur = cpu_limit;
            r_cpu.rlim_max = RLIM_INFINITY;
            r_mem.rlim_cur = mem_limit * 1024;
            r_mem.rlim_max = RLIM_INFINITY;

            setrlimit(RLIMIT_CPU, &r_cpu);
            setrlimit(RLIMIT_AS, &r_mem);
        }

    };
}